import { t } from 'i18next'
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import { IconTips, StyledWrap } from './style'
import StyleChooseSelect from './StyleChooseSelect'
import { useSinglePollStore } from '@/components/SinglePollModal/store'
import { StyledView } from './style'
import { initData, StyleData, allVmpStyleData } from './interface'
import { DragDropContextProvider } from '@/plugins/dnd'
import { Modal } from '@kedacom/react-next'
import Alert from '@/components/Alert'
// import { Poll, VmpMember } from '../interface'
import { MemberItem } from './item'
// import { useTableAllStore } from '../../main/table/all/store'
// import { useVmpTypeStore } from '../store.get'
import { Poll, VmpMemberEntity } from '../interface'
import { UserEntity } from '@/api/create/interface'
import shallow from 'zustand/shallow'
import { useMeetingVmpStore } from '../store'
import SinglePollModal, { SinglePollData } from '../../../components/SinglePollModal'
import { useBasicInfoStore } from '../../basicInfo/store'
import { UserModel } from '../../user/interface'
type ScrollBarProps = {
	/** 是否显示样式选择滚动条 */
	isShowScrollBar?: boolean
	/** 样式是否可选择 */
	isBarDisabled?: boolean
	/** 画面合成样式滑轮显示个数 */
	scrollLength?: number
	/** 容器 */
	container?: HTMLDivElement | null
}
type BoxProps = {
	/** 是否显示样式选择框 */
	isShowBox?: boolean
	/** 样式选择框是否可操作 */
	isBoxDisabled?: boolean
	/** 选择框设置项显示隐藏 */
	/** 只可从外部拖入，不可相互拖拽 */
	onlyDragIn?: boolean
	/** 是否显示加号图标 */
	noAddIcon?: boolean
	/** 样式框修改 */
	onBoxChange?: () => void
}
export type VmpViewProps = {
	layout: number
	// members: VmpMemberEntity[]
	disabled?: boolean
	mode?: number
} & ScrollBarProps &
	BoxProps
function VmpView(props: VmpViewProps, ref: any) {
	const {
		layout: orgStyle,
		disabled = false,
		isShowScrollBar = true,
		isBoxDisabled = false,
		noAddIcon = false,
		onlyDragIn = false,
		container,
		onBoxChange,
	} = props
	const [styleData, setStyleData] = useState(allVmpStyleData[0]) //当前样式数据
	// const [memberList, setMemberList] = useState<VmpMemberEntity[]>([])
	const setMemberList = (arr: VmpMemberEntity[]) => {
		update({ members: arr })
	}
	const { update, memberList, needUpdate } = useMeetingVmpStore(
		(state) => ({
			update: state.update,
			memberList: state.members,
			needUpdate: state.needUpdate,
		}),
		shallow
	)
	const [curPollData, setCurPollData] = useState<SinglePollData>({ index: 0, poll: null })
	const [open, setOpen] = useState(false)
	const getStyleData = (style: number) => allVmpStyleData.find((item) => item.id === style) ?? allVmpStyleData[0]
	/**初始化内容(分格和定制成员数据) */
	useEffect(() => {
		let curStyleData = getStyleData(orgStyle)
		let data: VmpMemberEntity[] = new Array(curStyleData.listItemCount).fill({}).map((_, index) => {
			let x = memberList.find((item) => item.chn_idx === getChnidx(index, curStyleData)) ?? initData
			return {
				...x,
				name: x.name,
			}
		})
		setStyleData(curStyleData)
		setMemberList(data)
	}, [orgStyle, needUpdate])
	/**下拉选择确认*/
	const vmpStyleSelect = (id: number) => {
		let curStyleData = getStyleData(id)
		let data = new Array(curStyleData.listItemCount).fill({}).map((_, index) => {
			let x: VmpMemberEntity = memberList.find(
				(item) => item.chn_idx === getChnidx(index, curStyleData) && item.member_type !== 0
			) ?? { ...initData }
			return {
				...x,
				name: x.name,
			}
		})
		setStyleData(curStyleData)
		setMemberList(data)
		update({ layout: id })
	}
	const getChnidx = (index: number, data?: StyleData) => {
		let obj = data ?? styleData
		return obj.order ? obj.order[index] - 1 : index
	}
	type DropDataMt = UserEntity
	interface DropData<T = DropDataMt, K = { [key: string]: any }> {
		data?: {
			mt?: T
		} & K
		from?: string
		index?: number
	}
	const handleDrop = (dataTransfer: DropData, index: number) => {
		if (props.mode === 4) {
			return
		}
		let dragFromListName = dataTransfer.from
		let sourceData: UserEntity = dataTransfer.data?.mt as UserEntity
		let rowData: UserModel = dataTransfer.data?.rowData as UserModel
		let newArr = [...memberList]
		if (dragFromListName === 'all-user') {
			if (rowData) {
				//超大方会议只有互动终端才能拖拽进去
				if (useBasicInfoStore.getState().superMtNum && !rowData.status.isInteractive) {
					return
				}
			}
			newArr[index] = {
				member_type: 1,
				chn_idx: getChnidx(index),
				account: sourceData.account,
				account_type: sourceData.account_type,
				name: sourceData.name,
				conf_e164: sourceData.conf_e164 || sourceData.parent_id || '',
			}
		} else if (dragFromListName === 'vmpItem' && !onlyDragIn) {
			//在风格内部相互拖拽
			let sourceIndex = dataTransfer.index
			if (newArr[index].member_type === 6 || sourceIndex === undefined) return
			if (newArr[index].member_type !== 0) {
				//todo name计算属性，后面版本修复
				let temp = { ...newArr[index], name: newArr[index].name, chn_idx: getChnidx(sourceIndex) }
				newArr[index] = { ...newArr[sourceIndex], name: newArr[sourceIndex].name, chn_idx: getChnidx(index) }
				newArr[sourceIndex] = temp
			} else {
				//todo name计算属性，后面版本修复
				newArr[index] = { ...newArr[sourceIndex], name: newArr[sourceIndex].name, chn_idx: getChnidx(index) }
				newArr[sourceIndex] = { ...initData }
			}
		}
		setMemberList(newArr)
		onBoxChange?.()
	}
	const onTypeSelect = (index: number, name: string, type: number, member: VmpMemberEntity) => {
		if (type === 6) {
			setCurPollData({
				index: index,
				poll: member.poll ?? null,
			})
			setOpen(true)
			return
		}
		if (type === 2 || type === 3 || type === 4 || type === 7) {
			if (memberList.find((item) => item.member_type === type)) {
				Alert(t('在其他通道已经设置了{{name}}', { name: name }))
				return
			}
		}
		var newList = [...memberList]
		newList[index] = {
			name: '',
			chn_idx: getChnidx(index),
			member_type: type,
		}
		setMemberList(newList)
		onBoxChange?.()
	}
	const onType6Select = (index: number, poll?: Poll) => {
		var newList = [...memberList]
		newList[index] = {
			name: '',
			chn_idx: getChnidx(index),
			member_type: 6,
			poll,
		}
		setMemberList(newList)
		onBoxChange?.()
	}
	const clearVmpMember = (index: number) => {
		let newArr = [...memberList]
		newArr[index] = { ...initData }
		setMemberList(newArr)
		onBoxChange?.()
	}
	//获取总轮询人数
	const getPollMembersNum = () => {
		let count = 0
		memberList.forEach((member) => {
			if (member.member_type === 6 && member.poll && member.poll.members.length !== 0) {
				count += member.poll.members.length
			}
		})
		return count
	}
	useImperativeHandle(ref, () => ({
		getValue() {
			return memberList.filter((i) => !(!i.account && i.member_type === 0))
		},
		getStyle() {
			return styleData.id
		},
	}))
	return (
		<StyledWrap className="vmp-select-box">
			{(props.mode === 1 || props.mode === 4) && isShowScrollBar && (
				<StyleChooseSelect
					container={container}
					styleData={styleData}
					onSelect={vmpStyleSelect}
					isShowSingle={false}
					disabled={false}
				/>
			)}
			{props.mode === 1 && (
				<DragDropContextProvider>
					<StyledView disabled={isBoxDisabled} scale={1} className="style-container">
						<div className={`vmp-list ${styleData.className}`} data-key={styleData.dataKey}>
							{memberList.map((member, index) => {
								return (
									<MemberItem
										key={`${index}$${member.member_type}$${member.account}`}
										index={index}
										dataKey={styleData.order ? styleData.order[index] : index + 1}
										member={member}
										noAddIcon={noAddIcon}
										disabled={isBoxDisabled || disabled}
										onTypeSelect={onTypeSelect}
										onDrop={handleDrop}
										onClearVmpMember={clearVmpMember}
									/>
								)
							})}
						</div>
					</StyledView>
				</DragDropContextProvider>
			)}
			{props.mode === 1 && (
				<div className="tip">
					<IconTips></IconTips>
					<span className="msg">{t('请拖拽与会方至指定的画面中')}</span>
				</div>
			)}
			<Modal
				className="single-poll-modal"
				open={open}
				title={t('单通道轮询')}
				needFooter={false}
				width={850}
				height={612}
				onCancel={() => {
					setOpen(false)
					useSinglePollStore.getState().reset()
				}}
			>
				<SinglePollModal
					setOpen={setOpen}
					data={curPollData}
					okCallBack={(data: SinglePollData) => {
						onType6Select(data.index, data.poll ?? undefined)
					}}
					getPollMembersNum={getPollMembersNum}
				/>
			</Modal>
		</StyledWrap>
	)
}
export default forwardRef(VmpView) as (props: VmpViewProps & { ref?: any }) => React.ReactElement
